import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author LKQ
 * @date 2021/12/30 15:04
 * @description
 */
public class Solution2 {
    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        int[] nums = {-1, 0, 1, 2, -1, -4};
        solution2.threeSum(nums);
    }

    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        // 枚举a
        for (int i = 0; i < n - 2; i++) {
            // 去重
            if (i > 0 && nums[i] == nums[i-1]) {
                continue;
            }
            int target = -nums[i];
            int left = i+1, right = n-1;
            while (left < right) {
                if (nums[left] + nums[right] < target) {
                    left++;
                }else if (nums[left] + nums[right] > target) {
                    right--;
                }else {
                    // 快速生成list, 不需要add。
                    ans.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    // 去重
                    while (left < n-1 && nums[left] == nums[++left]) { }
                    while (right > left && nums[right] == nums[--right]) { }

                }
            }
        }
        return ans;
    }
}
